<script setup lang="ts">
// 获取屏幕边界到安全区域距离
// import type { OrderItem, OrderListParams, OrderListResult } from '@/types/order'
import {onMounted, ref} from 'vue'

import type {CreateOrder, OrderRespPageData, PayOrdersReqPageData} from "@/api/orders/types";
import {getPayAliInfo, getPayOrdersPage, getPayWeChatInfo, queryPayAliResult, updatePayOrders} from "@/api/orders";
import {OrderState, orderStateList} from "@/types/constants";
import {publicUrl} from "@/stores";
import formatDate from "../../../utils/utils";
import {htmlEscape} from "@/utils/codeConversion";

const {safeAreaInsets} = uni.getSystemInfoSync()

const props = defineProps<{
  // 订单状态，1为待付款、2为待发货、3为待收货、4为待评价、5为已完成、6为已取消
  orderState: number
}>()

const queryParams: PayOrdersReqPageData = {
  pageNo: 1,
  pageSize: 4,
}
const orderSize = ref(0)
const orderList = ref<CreateOrder[]>([])
const nextPage = () => {
  if (queryParams.pageNo * queryParams.pageSize >= orderSize.value) {
    uni.showToast({title: '没有更多订单了', icon: 'none'})
    return
  }
  queryParams.pageNo++
  getOrderList()
}
// 获取数据
const getOrderList = async () => {
  const orderStatusParam = props.orderState === -1 ? '' : props.orderState.toString()
  getPayOrdersPage({
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    orderStatus: orderStatusParam // 明确赋值避免潜在类型问题
  }).then(res => {
    orderList.value.push(...res.data.list)
    orderSize.value = res.data.total
    // 添加调试日志验证数据
    console.log('接收到订单总数:', res.data.total, '当前页数据:', orderList.value.length)
  })

}

const ali = ref('')
const wx = ref('')

// 订单支付
const onOrderPay = async (id: string) => {
  await getPayAliInfo(id).then(responseData => {
    ali.value = responseData.data;  //从服务器获取的订单
  })
  await getPayWeChatInfo(id).then(responseData => {
    wx.value = responseData.data;  //从服务器获取的订单
  })
  uni.getProvider({
    service: 'payment',
    success: function (res) {
      console.log(res.provider, ali.value)
      if (res.provider.indexOf('alipay') != -1) {
        // var EnvUtils = plus.android.importClass('com.alipay.sdk.app.EnvUtils');
        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        // console.log(EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX));

        // 直接调用支付宝小程序支付的方式
        my.tradePay({
          orderStr: ali.value,
          success: res => {
            console.log('success:' + JSON.stringify(res));
            if (res.resultCode === '9000') {
              queryPayAliResult(id).then((res) => {
                if (res.data === 'TRADE_SUCCESS') {
                  uni.showToast({
                    icon: 'success',
                    title: '支付成功',
                    duration: 2000,
                    success: () => {
                      // 关闭当前页，再跳转支付结果页
                      uni.redirectTo({url: `/pagesOrder/payment/payment?id=${id}`})
                    },
                  });
                } else {
                  uni.showToast({
                    title: '支付失败',
                    icon: 'error',
                  })
                }
              })
            }else {
              // 支付失败
              uni.showToast({
                title: '支付失败',
                icon: 'error',
              })
            }
          },
          fail: error => {
            console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
          },
        });

      } else if (res.provider.indexOf('wxpay') != -1) {

        uni.requestPayment({
          "provider": "wxpay",
          "orderInfo": wx.value,
          success(res) {
            console.log("支付成功", res);
          },
          fail(e) {
            console.log('支付失败:' + JSON.stringify(e));
          }
        })
      }
      // 关闭当前页，再跳转支付结果页
      uni.redirectTo({url: `/pagesOrder/payment/payment?id=${id}`})
    },
    fail(e) {
      console.log('支付失败:' + JSON.stringify(e));
    }
  });
  // 通过环境变量区分开发环境
  // if (import.meta.env.DEV) {
  //   // 开发环境：模拟支付，修改订单状态为已支付
  //   await getPayMockAPI({ orderId: id })
  // } else {
  //   // 生产环境：获取支付参数 + 发起微信支付
  //   const res = await getPayWxPayMiniPayAPI({ orderId: id })
  //   await wx.requestPayment(res.result)
  // }
  // // // 关闭当前页，再跳转支付结果页
  // // uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${id}` })
  // uni.showToast({ title: '支付成功', icon: 'success' })
  // let find = orderList.value?.find((item) => item.id === id)
  // find!.orderStatus = OrderState.DaiFaHuo
}
// 确认收货
const onOrderConfirm = (val: CreateOrder) => {
  // 二次确认弹窗
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        val.orderStatus = '100'
        val.orderItems?.forEach((item) => {
          if (item.product.description != null) {
            item.product.description = htmlEscape(item.product.description)
          }
        })
        const res = await updatePayOrders(val)
        if (res.data) {
          await getOrderList()
        }else {
          uni.showToast({
            title: '系统出现故障，收货失败，稍后再试',
            icon: 'error',
          })
        }
        // 更新订单状态
        // order.value = res.result
      }
    },
  })
}


onMounted(async () => {
  await getOrderList()
})
</script>

<template>
  <scroll-view scroll-y="true" class="orders" @scrolltolower="nextPage">
    <!--    <view >-->
    <view class="card" v-for="item in orderList" :key="item.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ formatDate(item.createTime) }}</text>
        <!-- 订单状态文字 -->
        <text v-if="item.orderStatus == OrderState.DaiFuKuan">待付款</text>
        <text v-if="item.orderStatus == OrderState.YiQuXiao">已取消</text>
        <text v-if="item.orderStatus == OrderState.DaiFaHuo">待收货</text>
        <!--          <text v-if="item.orderStatus == OrderState.DaiPingJia">待评价</text>-->
        <text v-if="item.orderStatus == OrderState.YiWanCheng">已完成</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <!--        <text v-if="item.orderStatus >= OrderState.DaiPingJia" class="icon-delete"></text>-->
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
          v-for="sku in item.orderItems"
          :key="sku.id"
          class="goods"
          :url="`/pagesOrder/detail/detail?id=${item.bh}`"
          hover-class="none"
      >
        <view class="cover">
          <image mode="aspectFit" :src="publicUrl+sku.product.photo"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">
            {{ sku.product.name }}
            <text style="margin-left: 20rpx;">x{{ sku.quantity }}</text>
          </view>
          <view class="type">￥{{ item.amount?.toFixed(2) }}</view>

        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ item.orderItems?.length }}件商品</text>
        <text>实付</text>
        <text class="amount">
          <text class="symbol">¥</text>
          {{ item.amount?.toFixed(2) }}
        </text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="item.orderStatus == OrderState.DaiFuKuan">
          <view class="button primary" @tap="onOrderPay(item.bh)">去支付</view>
        </template>
        <template v-else>
          <navigator
              class="button secondary"
              :url="`/pagesOrder/create/create?skuId=${item.orderItems[0].productId}&count=${item.orderItems[0].quantity}`"
              hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view v-if="item.orderStatus == OrderState.DaiFaHuo" @click="onOrderConfirm(item)" class="button primary"
          >确认收货
          </view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ orderSize >= orderList?.length ? '没有更多数据~' : '正在加载...' }}
    </view>
    <!--    </view>-->
  </scroll-view>
</template>

<style scoped lang="scss">
// 订单列表
.orders {
  //.scroll-area {
  height: calc(100vh - 100rpx);
  overflow-y: scroll; /* 显示垂直滚动条 */
  //}
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;

    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;

      image {
        width: 100rpx;
        height: 100rpx;
      }
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 50rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #ff0000;
      //background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>